package v1

import (
	"copper-cloud/models"
	"copper-cloud/pkg/app"
	"copper-cloud/pkg/e"
	"copper-cloud/pkg/logging"
	"copper-cloud/pkg/util"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func AddDept(c *gin.Context) {
	traceId := util.GetTraceID(c)
	appG := app.Gin{C: c}

	deptName := c.Query("dept_name")

	if deptName == "" {
		appG.Response(http.StatusBadRequest, e.InvalidParams, traceId, nil)
		return
	}

	d := models.Dept{
		DeptName: deptName,
	}

	isExisted := models.CheckDeptIsExisted(deptName)

	if isExisted {
		appG.Response(http.StatusBadRequest, e.InvalidParams, traceId, nil)
		return
	}

	err := models.DeptInsert(d)

	if err != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR, traceId, nil)
		return
	}

	appG.Response(http.StatusOK, e.SUCCESS, traceId, nil)

}

func GetAllDepts(c *gin.Context) {

	traceId := util.GetTraceID(c)
	appG := app.Gin{C: c}

	httpCode := http.StatusOK
	errCode := e.SUCCESS

	depts, err := models.DeptSelects()
	if err != nil {
		httpCode = http.StatusInternalServerError
		errCode = e.ERROR

		appG.Response(httpCode, errCode, traceId, nil)
		return
	}

	appG.Response(httpCode, errCode, traceId, depts)
}

func GetDeptById(c *gin.Context) {
	traceId := util.GetTraceID(c)
	appG := app.Gin{C: c}

	httpCode := http.StatusOK
	errCode := e.SUCCESS

	deptId, paramErr := strconv.Atoi(c.Param("dept_id"))
	logging.ZapLogger.Info("deptId: ", deptId)

	if paramErr != nil {
		httpCode = http.StatusBadRequest
		errCode = e.ErrorDeptIdMustBeInt

		appG.Response(httpCode, errCode, traceId, nil)
		return
	}

	dept, err := models.GetDeptNameById(deptId)
	if err != nil {
		httpCode = http.StatusInternalServerError
		errCode = e.ERROR

		appG.Response(httpCode, errCode, traceId, nil)
		return
	}
	// dept为空，则表示没有找到数据
	if dept == nil {

		appG.Response(http.StatusBadRequest, e.ErrorDeptNotFound, traceId, nil)
		return
	}

	appG.Response(httpCode, errCode, traceId, dept)

}